import Vue from 'vue'
import Vuex from 'vuex'
import socket from '../socket'

Vue.use(Vuex)

const state = {
  nickname: '' || localStorage.getItem('nickname'),
  nicknames: [],
  holder: '' || localStorage.getItem('holder'),
  lines: [],
  isGameConnect: false
}

const mutations = {
  SET_NICKNAME(state, nickname) {
    state.nickname = nickname
  },
  SET_NICKNAMES(state, nicknames) {
    state.nicknames = nicknames
  },
  SET_HOLDER(state, holder) {
    state.holder = holder
  },
  SET_LINES(state, lines) {
    state.lines = lines
  },
  UPDATE_NICKNAMES(state, nickname) {
    if (!state.nicknames.includes(nickname)) {
      this.state.nicknames.push(nickname)
    }
  },
  UPDATE_ISGAMECONNECT(state, status) {
    state.isGameConnect = status
  },
  EXIT_NICKNAMES(state, nickname) {
    const index = state.nicknames.indexOf(nickname)
    state.nicknames.splice(index, 1)
  },
  UPDATE_LINES(state, line) {
    state.lines.push(line)
  },
  UPDATE_LASTlINE(state, line) {
    state.lines[state.lines.length - 1].points = line
  }
}

const actions = {
  checkNickname({ commit }, nickname) {
    return new Promise((resolve, reject) => {
      socket.emit('check_user_exist', nickname, (res) => {
        resolve(res)
        if (!res) {
          commit('SET_NICKNAME', nickname)
          localStorage.setItem('nickname', nickname)
        }
      })
    })
  },
  enterGame() {
    const nickname = localStorage.getItem('nickname')
    socket.emit('enter', nickname)
  },
  exitGame() {
    socket.emit('leave')
  },
  startGame({ commit }, imageName) {
    socket.emit('start_game', imageName)
    commit('SET_HOLDER', imageName)
  },
  stopGame() {
    socket.emit('stop_game')
  },
  drawLine({ commit }, line) {
    socket.emit('new_line', line)
    commit('UPDATE_LINES', line)
  },
  updateLine({ commit }, line) {
    socket.emit('update_line', line)
    commit('UPDATE_LASTlINE', line)
  },
  sendAnswer({ commit }, answer) {
    socket.emit('answer_game', answer)
  }
}

const getters = {
  nickname: () => state.nickname,
  nicknames: () => state.nicknames,
  holder: () => state.holder,
  isGameConnect: () => state.isGameConnect,
  isHolder: () => !!state.holder

}

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
